package org.example.view.admin;

import org.example.controller.AdminController;
import org.example.data.Result;
import org.example.data.Room;
import org.example.data.UserWithDetails;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AddRoom extends JFrame {
    private JTextField txtName, txtFloor, txtPrice;
    private JButton btnSave;
    private UserWithDetails user;

    public AddRoom(UserWithDetails user) {
        super("添加房间");
        this.user = user;
        initUI();
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridLayout(4, 2));

        JLabel lblName = new JLabel("房间名称:");
        JLabel lblFloor = new JLabel("楼层:");
        JLabel lblPrice = new JLabel("价格:");

        txtName = new JTextField();
        txtFloor = new JTextField();
        txtPrice = new JTextField();

        btnSave = new JButton("保存");
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = txtName.getText();
                String floor = txtFloor.getText();
                double price = Double.parseDouble(txtPrice.getText()); // 注意异常处理

                Room room = new Room(name, floor, price); // 假设Room构造函数允许空状态
                AdminController adminController = new AdminController();
                Result<Integer> result = adminController.addRoom(room);
                if (result.getStatus()) {
                    JOptionPane.showMessageDialog(AddRoom.this, "房间添加成功！");
                    SwingUtilities.invokeLater(() -> new AdminIndex(user).setVisible(true));
                    dispose(); // 关闭窗口
                } else {
                    JOptionPane.showMessageDialog(AddRoom.this, result.getMessage());
                }
            }
        });

        panel.add(lblName);
        panel.add(txtName);
        panel.add(lblFloor);
        panel.add(txtFloor);
        panel.add(lblPrice);
        panel.add(txtPrice);
        panel.add(new JLabel()); // 填充
        panel.add(btnSave);

        add(panel);
    }

}
